package com.pvdnc.nsocket.server;

import com.pvdnc.nsocket.EndPoint;
import com.pvdnc.nsocket.init.CSInitializer;
import com.pvdnc.nsocket.log.SLog;
import com.pvdnc.nsocket.protocol.base.Packet;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public abstract class BaseServer extends CSInitializer {
    public static final SLog LOG=new SLog(BaseServer.class);

    public BaseServer(EndPoint endPoint) {
        super(endPoint);
    }

    private ServerBootstrap getDefault(){
        ServerBootstrap bootstrap=new ServerBootstrap();
        //配置服务启动参数
        bootstrap
                .group(mAcceptLoop,mClientLoop)
                .channel(NioServerSocketChannel.class)
                //配置服务器参数
                .option(ChannelOption.SO_BACKLOG, 1024)

                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.childHandler(this);
        return bootstrap;
    }

    public abstract void onBind();

    public void doBind() {
        getDefault().bind(getHost(),getPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if(!future.isSuccess())
                    throw new IllegalStateException("fail to bind",future.cause());
                setChannel(future.channel());
                onBind();
            }
        });
    }
}
